<script setup>
    import { computed, reactive, ref, unref, watch, nextTick, onMounted } from 'vue'
    import { CloseOutlined, PlusOutlined } from '@ant-design/icons-vue'
    import ElectronWindowViewer from './modules/ElectronWindowViewer.vue'
    import AccountAddModal from './modules/AccountAddModal.vue'
    import { useTemplateRefsList } from '@vueuse/core'
    import request from '@/common/utils/request'
    import { find, findIndex, first, cloneDeep } from 'lodash-es'

    const accounts = ref([])
    const total = ref(0)

    const appPages = ref([])
    const activeAppPage = ref()
    const appPageTabRefs = useTemplateRefsList()
    const addAccountVisible = ref(false)
    let searchKeyword = ref('')
    const queryRef = reactive({
        page: 1,
        pageSize: 10,
        nickname:''
    })
    const activeAppPageHistory = ref()

const showAppPage = async (app) => {
        if (! find(appPages.value, { id: app.id })) {
            let electronAppPage = await createElectronAppPage(app)
            appPages.value.push(electronAppPage)
            activeAppPage.value = electronAppPage
        } else if(! activeAppPage.value || activeAppPage.value.id != app.id) {
            activeAppPage.value = app
        }
    }

    const createElectronAppPage = async (app) => {
        let cookie = app.third_param.cookie
        let comment_url = app.platform.comment_url

        if(app.source == 'xiaohongshu'){
            const xhs_cookie = localStorage.getItem(`app_xhs_cookie_${app.id}`)

            if(xhs_cookie){
                cookie = JSON.parse(xhs_cookie)
            }
        }

        if(app.source == 'douyin' && app.user_expand_info?.account_type == 'org_sub'){
          comment_url = 'https://creator.douyin.com'
        }

        return {
            ...app,
            electron: {
                url: comment_url,
                option: {
                    cookie
                }
            }
        }
    }

    const onAppClose = (appId) => {
        let index = findIndex(appPages.value, { id: appId })

        if (activeAppPage.value.id == appId) {
            if(appPages.value.length == 1){
                activeAppPage.value = null
            } else if(index == appPages.value.length - 1){
                activeAppPage.value = appPages.value[index - 1]
            } else {
                activeAppPage.value = appPages.value[index + 1]
            }
        }

        appPages.value.splice(index, 1)
    }

    const onCloseAppAll = () => {
        appPages.value = []
        activeAppPage.value = null
    }

    const getAccountList = async () => {
        let params = {
            page: queryRef.page,
            pageSize: queryRef.pageSize,
            nickname: searchKeyword.value
        }
        const { result: { total: dataTotal, data } } = await request.get('/work_ai', '/org/platform/account/user/list', params)

        accounts.value = data
        total.value = dataTotal
    }
    const onSearch = ()=>{
        getAccountList()
    }
    const activeAppPageIndex = computed(() => {
        return activeAppPage.value ? findIndex(appPages.value, { id: activeAppPage.value.id }) : null
    })


    const onAccountLogined = () => {
        getAccountList()
    }

    watch(activeAppPage, async (appPage) => {
      if(appPage){
        await nextTick()

        let index = findIndex(appPages.value, { id: appPage.id })
        appPageTabRefs.value[index].scrollIntoView({
            behavior: 'smooth',
            block: 'center',
            inline: 'center'
        })
      }
    })

    watch(addAccountVisible, (visible) => {
      if (! visible && activeAppPageHistory.value) {
        activeAppPage.value = cloneDeep(unref(activeAppPageHistory))
      }
    })

    watch(() => queryRef.page, () => {
      getAccountList()
    })

    const initData = async () => {
        await getAccountList()

        if((! activeAppPage.value) && accounts.value.length > 0){
            showAppPage(first(accounts.value))
        }
    }

    const addAccountHandler = async () => {
        if(activeAppPage.value){
            activeAppPageHistory.value = cloneDeep(unref(activeAppPage))
            activeAppPage.value = null
        }
        await nextTick()
        addAccountVisible.value = true
    }

    const onAppBrowerInit = (browerViewer) => {
        if(activeAppPage.value.source == 'xiaohongshu'){
            browerViewer.beforeRequest("https://edith.xiaohongshu.com/api/sns/web/v2/user/me", async ({headers}) => {
              localStorage.setItem(`app_xhs_cookie_${activeAppPage.value.id}`, JSON.stringify(headers.Cookie))
            })
        }

        if(activeAppPage.value.source == 'douyin' && activeAppPage.value.user_expand_info?.account_type == 'org_sub'){
          browerViewer.navigateTo('https://creator.douyin.com/following/comment')
        }
    }

    onMounted(() => {
        initData()
    })
</script>

<template>
    <div class="flex box pagewarp">
        <div class="flex flex-col menu">
            <div>
                <div class="p-10">
                    <div class="flex gap-10">
                        <a-input-search
                        v-model:value="searchKeyword"
                        placeholder="搜索账号"
                        size="small"
                        style="width: 250px"
                        @search="onSearch"
                        />
                        <!-- <a-button size="small" style="padding: 0px 7px;"><template #icon><left-outlined /></template></a-button> -->
                    </div>
                </div>
            </div>
            <div class="flex-1 overflow-hidden">
                <div class="h-full overflow-y-auto">
                    <div
                        class="flex py-10 mb-5 cursor-pointer px-15 online gap-15 account-item"
                        v-for="(account) in accounts"
                        :key="account.id"
                        @click="showAppPage(account)"
                        :class="{
                            active: !! (find(appPages, { id: account.id }))
                        }"
                    >
                        <div class="relative account-avatar">
                            <img :src="account.avatar" width="30" height="30"/>

                            <div style="position: absolute;top: 22px;left: 14px;">
                                <img :src="account.platform.image" width="20" height="20"/>
                            </div>
                        </div>
                        <div class="flex-1">
                            <div class="flex" style="font-size: 12px;">
                                <span class="account-nickname">{{ account.nickname }}</span>
                            </div>
                            <div class="flex mt-2 align-center">
                                <div class="account-source">
                                    {{ account.source_txt }}
                                </div>
                                <div style="margin-left: 5px; display: flex;">
                                    <a-tag :color="account.status ? 'green' : 'red'">{{ account.status_txt }}</a-tag>
                                    <a-tag v-if="account.user_expand_info&&account.user_expand_info.account_type=='org_main'"  color="purple">主</a-tag>
                                    <a-tag  v-if="account.user_expand_info&&account.user_expand_info.account_type=='org_sub'" color="blue">子</a-tag>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="pt-10 menu-footer">
                <div class="flex justify-center">
                    <a-pagination v-model:current="queryRef.page" :defaultPageSize="queryRef.pageSize" simple :total="total" />
                </div>
                <!-- <div class="flex justify-center mt-10">
                    <a-button style="width: 110px;" @click="addAccountHandler">
                        <PlusOutlined />
                        添加账号
                    </a-button>
                </div> -->
            </div>
        </div>
        <div class="flex-1 overflow-hidden" style="background-color: #ffffff;">
            <div class="flex flex-col h-full" v-if="appPages.length > 0">
                <div class="flex justify-between gap-10 pr-10 account-tabs">
                    <div class="flex-1 pt-10 overflow-hidden">
                        <div class="flex w-full pl-10 overflow-x-auto tabs" style="position: relative;">
                            <div class="w-10 h-full account" :class="{ prev: activeAppPageIndex == 0 }" style="position: absolute;left: 0px;bottom: 0px;"><div class="p-0 tab-item"></div></div>
                            <div
                                class="flex account align-center"
                                v-for="(app, index) in appPages" :key="app.id"
                                :class="{
                                    active: app.id == activeAppPage?.id,
                                    prev: index == activeAppPageIndex - 1,
                                    after: index == activeAppPageIndex + 1
                                }"
                                :ref="appPageTabRefs.set"
                                @click="() => showAppPage(app)"
                            >
                                <div class="flex gap-5 cursor-pointer tab-item">
                                        <div>
                                            <img :src="app.platform.image" width="18" height="18" style="border: 1px solid #ccc; border-radius: 50%;"/>
                                        </div>
                                        <div style="white-space: nowrap;">
                                            {{ app.source_txt }}-{{ app.nickname }}
                                        </div>
                                        <div @click.stop="onAppClose(app.id)">
                                            <close-outlined />
                                        </div>
                                </div>
                                <div class="line"></div>
                            </div>
                            <div class="w-10 account" :class="{ after: activeAppPageIndex == appPages.length - 1 }"><div class="p-0 tab-item">&nbsp;&nbsp;&nbsp;</div></div>
                        </div>
                    </div>
                    <div class="flex align-center">
                        <a-button size="small" style="font-size: 12px;border-radius: 8px;" @click="onCloseAppAll">关闭全部</a-button>
                    </div>
                </div>
                <div class="flex-1">
                    <div
                        class="w-full h-full"
                        v-for="(app) in appPages"
                        :key="app.id"
                        v-show="app.id == activeAppPage?.id"
                    >
                        <electron-window-viewer
                            :app-key="app.source"
                            :url="app.electron.url"
                            :auth_url="app.platform.listen_url"
                            :option="app.electron.option"
                            @browerInit="onAppBrowerInit"
                            @logined="onAccountLogined"
                        >
                        </electron-window-viewer>
                    </div>
                </div>
            </div>
            <div class="flex justify-center h-full align-center" v-else>
                <a-empty description="请选择账号"/>
            </div>
        </div>

        <Suspense>
            <account-add-modal v-model:visible="addAccountVisible" @logined="onAccountLogined"></account-add-modal>
        </Suspense>
    </div>
</template>

<style lang="less" scoped>
    .pagewarp {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
        height: 100%;
        .menu {
            width: 250px;
            background-color: #f8f8f8;
            padding-bottom: 10px;


            .account-item {
                &:hover, &.active {
                    background-color: #e4e4e4;
                }

                .account-avatar {
                    img {
                        border-radius: 50%;
                        border: 1px solid #ccc;
                    }
                }

                .account-source {
                    background-color: #e4e4e4;
                    display: inline;
                    padding: 2px 6px;
                    font-size: 12px;
                    border-radius: 10px;
                    color: #6a6a6a;
                    min-width: 50px;
                    text-align: center;
                }
            }

            &-footer {
                border-top: 1px solid #ccc;
            }
        }
    }
    .account-tabs {

        background-color: #dadada;
        font-size: 12px;

        .tabs {
            &::-webkit-scrollbar:horizontal {
                // height: 10px;
            }
        }

        .account {
            background-color: #fff;

            .tab-item {
                height: 100%;
                padding: 7px 10px;
                background-color: #dadada;
            }


            &.active {
                background-color: #dadada;

                .tab-item {
                    background-color: #fff;
                    border-radius: 10px 10px 0px 0px;
                }

                .line {
                    display: none;
                }
            }

            &.prev {
                .tab-item {
                    border-radius: 0px 0px 5px 0px;
                }

                .line {
                    display: none;
                }
            }

            &.after {
                .tab-item {
                    border-radius: 0px 0px 0px 5px;
                }
            }

            .line {
                height: 100%;
                background-color: #dadada;
                display: flex;
                align-items: center;

                &::after {
                    display: block;
                    content: "";
                    height: 18px;
                    width: 2px;
                    background-color: #9a9a9a;
                }
            }
        }
    }


    .p-0 {
        padding: 0px !important;
    }
</style>